package com.yyfax.ph.main;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.Loader;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;
import com.yyfax.common.CLog;
import com.yyfax.common.tools.IntentUtils;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.IEvent;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yyfax.ph.R;
import com.yyfax.ph.StatIDSet;
import com.yyfax.ph.base.AnalyticsActivity;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.common.location.LocationManager;
import com.yyfax.ph.common.utils.preferenceutils.PreferenceConstants;
import com.yyfax.ph.common.utils.preferenceutils.PreferenceManager;
import com.yyfax.ph.common.widgets.dialog.NoticeDialog;
import com.yyfax.ph.home.HomeFragment;
import com.yyfax.ph.home.imageupload.ImageIdManager;
import com.yyfax.ph.personal.PersonCenterFragment;
import com.yyfax.ph.personal.authority.jpush.JPushPresenter;
import com.yyfax.ph.personal.authority.jpush.PushEvent;
import com.yyfax.ph.personal.authority.jpush.PushInfoReceiver;
import com.yyfax.ph.personal.authority.login.LoginActivity;
import com.yyfax.ph.personal.authority.register.RegisterActivity;
import com.yyfax.ph.personal.update.UpdatePresenter;
import com.yyfax.ph.personal.update.UpdateService;
import com.yyfax.ph.products.ProductsFragment;
import com.yyfax.ph.progress.search.ProgressFragment;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


public class MainActivity extends AnalyticsActivity implements MainPresenter.View, UpdatePresenter.View, JPushPresenter.View, NoticeDialog.CloseNoticeListener, OnCheckedChangeListener {
	private static final String TAG = MainActivity.class.getSimpleName();

	private static final int LOADER_ID_UPDATE = 101;
	private static final int LOADER_ID_NOTICE = 102;
	private static final int LOADER_ID_J_PUSH = 902;

	public static final String CURRENT_ITEM = "currentItem";
	public static final String GO_LOGIN = "go_login";
	public static final String RETURN_PROGRESS_SEARCH = "return_progress_search";
	public static final String RETURN_HOME_FRAGMENT = "return_home_fragment";

	private static final String TAB_TAG_HOME_FRAGMENT = "tab_tag_home_fragment";
	private static final String TAB_TAG_PRODUCTS_FRAGMENT = "tab_tag_products_fragment";
	private static final String TAB_TAG_PROGRESS_FRAGMENT = "tab_tag_progress_fragment";
	private static final String TAB_TAG_PERSONAL_FRAGMENT = "tab_tag_personal_fragment";

	private static final int TAB_ID_HOME_FRAGMENT = 0;
	private static final int TAB_ID_PRODUCTS_FRAGMENT = 1;
	private static final int TAB_ID_PROGRESS_FRAGMENT = 2;
	private static final int TAB_ID_PERSONAL_FRAGMENT = 3;

	@BindView(R.id.fragment_container_fl)
	FrameLayout mFragmentContainerFl;
	@BindView(R.id.navigate_bar_recommend)
	RadioButton mMainBtn;
	@BindView(R.id.navigate_bar_products)
	RadioButton mProductsBtn;
	@BindView(R.id.navigate_bar_progress)
	RadioButton mProgressBtn;
	@BindView(R.id.navigate_bar_personal)
	RadioButton mPersonalBtn;
	@BindView(R.id.navigate_bar_container)
	RadioGroup radioGroup;

	private MainPresenter mNoticePresenter;
	private UpdatePresenter mUpdatePresenter;
	private JPushPresenter mJPushPresenter;

	private NoticeDialog mNoticeDialog;

	private Fragment mHomeFragment;
	private Fragment mProductsFragment;
	private Fragment mProgressFragment;
	private Fragment mPersonCenterFragment;

	private UpdateService mUpdateService;

	private long mFirstClickTime = 0;
	private int mCurrentItem = 0;

	public static void start(Activity aty) {
		Intent intent = new Intent(aty, MainActivity.class);
		aty.startActivity(intent);
	}

	public static void start(Activity aty, boolean goLoginPage) {
		Intent intent = new Intent(aty, MainActivity.class);
		intent.putExtra(GO_LOGIN, goLoginPage);
		aty.startActivity(intent);
	}

	public static void startToProgressSearch(Activity aty) {
		Intent intent = new Intent(aty, MainActivity.class);
		intent.putExtra(RETURN_PROGRESS_SEARCH, true);
		aty.startActivity(intent);
	}

	public static void startToHomeFragment(Activity aty) {
		Intent intent = new Intent(aty, MainActivity.class);
		intent.putExtra(RETURN_HOME_FRAGMENT, true);
		aty.startActivity(intent);
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_ID_UPDATE:
				return new PresenterLoader<>(this, new UpdatePresenter.Generator());
			case LOADER_ID_NOTICE:
				return new PresenterLoader<>(this, new MainPresenter.Generator());
			case LOADER_ID_J_PUSH:
				return new PresenterLoader<>(this, new JPushPresenter.Generator());
		}
		return null;
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOADER_ID_UPDATE:
				mUpdatePresenter = (UpdatePresenter) data;
				mUpdatePresenter.attach(this);
				mUpdatePresenter.checkUpdate();
				break;
			case LOADER_ID_NOTICE:
				mNoticePresenter = (MainPresenter) data;
				mNoticePresenter.attach(this);
				mNoticePresenter.setupPreferencesManager(this);
				mNoticePresenter.getRsaKey();
				mNoticePresenter.getConfig();
				break;
			case LOADER_ID_J_PUSH:
				mJPushPresenter = (JPushPresenter) data;
				mJPushPresenter.attach(this);
				break;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (null != mNoticeDialog && mNoticeDialog.isShowing()) {
			mNoticeDialog.dismiss();
		}

		if (null != mUpdateService) {
			mUpdateService.closeDialog();
		}

		getSupportLoaderManager().destroyLoader(LOADER_ID_NOTICE);
		getSupportLoaderManager().destroyLoader(LOADER_ID_UPDATE);
		getSupportLoaderManager().destroyLoader(LOADER_ID_J_PUSH);
		EventAgent.unregister(this);
		LocationManager.destroy();
	}

	@Override
	public int getContentViewRes() {
		return R.layout.activity_main;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getSupportLoaderManager().initLoader(LOADER_ID_UPDATE, null, this);
		getSupportLoaderManager().initLoader(LOADER_ID_NOTICE, null, this);
		getSupportLoaderManager().initLoader(LOADER_ID_J_PUSH, null, this);
		EventAgent.register(this);
		if (IntentUtils.getExtra(getIntent(), GO_LOGIN, false)) {//自动跳到登录页面
			LoginActivity.start(this);
		}
		mCurrentItem = TAB_ID_HOME_FRAGMENT;
	}

	@Override
	protected void onStart() {
		super.onStart();

		//todo 与GuideActivity的变量区分开
		PreferenceManager pm = YJPH.getInstance().getPreferenceManager();
		//判读是否登录， 是否已调用绑定极光接口，如果登录了 && 没调用绑定接口，则绑定极光
		if (pm.isLoginSuccess()) {
			if (!pm.isBindJPush()) {
				mJPushPresenter.bindJPush();
			}
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		if (null == intent ) {
			mCurrentItem = TAB_ID_HOME_FRAGMENT;
			showTab(mCurrentItem);
			return;
		}

		if (intent.getBooleanExtra(RETURN_HOME_FRAGMENT,false)) {
			mCurrentItem = TAB_ID_HOME_FRAGMENT;
		}
		if (intent.getBooleanExtra(PushInfoReceiver.FROM_PUSH_FLAG, false)
				|| intent.getBooleanExtra(RETURN_PROGRESS_SEARCH, false)) {
			mCurrentItem = TAB_ID_PROGRESS_FRAGMENT;
			if (mProgressFragment != null) {
				((ProgressFragment) mProgressFragment).setNeedRefresh(true);
			}
		}

		if (intent.getBooleanExtra(GO_LOGIN, false)) {//自动跳到登录页面
			LoginActivity.start(this);
		}

	}

	@SuppressLint("ResourceAsColor")
	public void initContentView() {
		setBtnBackVisible(false);
		setTitleVisible(true);
		setTopBarVisible(false);
		setTitleLeftVisible(false);
		setBtnRightVisible(false);
		showRegisterBtn();
		radioGroup.setOnCheckedChangeListener(this);
		showTab(TAB_ID_HOME_FRAGMENT);
		YJPH.getInstance().getPreferenceManager().savePreference(PreferenceConstants.SP_KEY_FIRST_FLAG, false);
	}


	@Override
	protected void onResume() {
		super.onResume();
		showRegisterBtn();
		if (!YJPH.getInstance().getPreferenceManager().isLoginSuccess() && mCurrentItem != TAB_ID_PRODUCTS_FRAGMENT) {
			showTab(TAB_ID_HOME_FRAGMENT);
		} else {
			showTab(mCurrentItem);
		}
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		if (savedInstanceState != null) {
			mCurrentItem = savedInstanceState.getInt(CURRENT_ITEM);
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(CURRENT_ITEM, mCurrentItem);
	}

	/**
	 * 点击右键 跳转到注册页面
	 */
	@Override
	public void onRightBtnPressed() {
		super.onRightBtnPressed();
		goToRegister();
	}

	/**
	 * 跳转到注册页面
	 */
	public void goToRegister() {
		RegisterActivity.start(this);
	}

	/**
	 * 已登录隐藏注册按钮，否则显示
	 */
	private void showRegisterBtn() {
		if (YJPH.getInstance().getPreferenceManager().isLoginSuccess()) {
			setBtnRightVisible(false);
		} else {
			setBtnRightVisible(true);
			setBtnRightTx(R.string.register);
		}
	}

	/**
	 * 点击底部按钮 未登录 情况下跳转到登录页面否则按原有逻辑跳转
	 */
	@Override
	public void onCheckedChanged(RadioGroup arg0, int id) {
		boolean loginSuccess = YJPH.getInstance().getPreferenceManager().isLoginSuccess();
		switch (id) {
			case R.id.navigate_bar_recommend:
				showTab(TAB_ID_HOME_FRAGMENT);
				break;
			case R.id.navigate_bar_products:
				showTab(TAB_ID_PRODUCTS_FRAGMENT);
				break;
			case R.id.navigate_bar_progress:
				if (loginSuccess) {
					if (mProgressFragment != null) {
						((ProgressFragment) mProgressFragment).setNeedRefresh(true);
					}
					showTab(TAB_ID_PROGRESS_FRAGMENT);
				} else {
					mCurrentItem = TAB_ID_HOME_FRAGMENT;
					LoginActivity.start(this);
				}
				break;
			case R.id.navigate_bar_personal:
				if (loginSuccess) {
					showTab(TAB_ID_PERSONAL_FRAGMENT);
				} else {
					mCurrentItem = TAB_ID_HOME_FRAGMENT;
					LoginActivity.start(this);
				}
				break;
		}
	}

	private void showTab(int page) {
		mCurrentItem = page;
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction ft = fm.beginTransaction();
		mHomeFragment = fm.findFragmentByTag(TAB_TAG_HOME_FRAGMENT);
		mProductsFragment = fm.findFragmentByTag(TAB_TAG_PRODUCTS_FRAGMENT);
		mProgressFragment = fm.findFragmentByTag(TAB_TAG_PROGRESS_FRAGMENT);
		mPersonCenterFragment = fm.findFragmentByTag(TAB_TAG_PERSONAL_FRAGMENT);
		if (mHomeFragment != null){
			ft.hide(mHomeFragment);
		}
		if (mProductsFragment != null){
			ft.hide(mProductsFragment);
		}
		if (mProgressFragment != null){
			ft.hide(mProgressFragment);
		}
		if (mPersonCenterFragment != null){
			ft.hide(mPersonCenterFragment);
		}

		switch (page) {
			case TAB_ID_HOME_FRAGMENT:
				StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_A001);
				setTopBarVisible(false);
				if (mHomeFragment == null){
					mHomeFragment = new HomeFragment();
					ft.add(R.id.fragment_container_fl, mHomeFragment, TAB_TAG_HOME_FRAGMENT);
				}else {
					ft.show(mHomeFragment);
					((HomeFragment)mHomeFragment).refreshRealTimeData();
				}
				mMainBtn.setChecked(true);
				if (mProgressFragment != null) {
					((ProgressFragment)mProgressFragment).dismissPopupWindow();
				}
				break;
			case TAB_ID_PRODUCTS_FRAGMENT:
				setTopBarVisible(false);
				mProductsBtn.setChecked(true);
				if (mProductsFragment == null){
					mProductsFragment = ProductsFragment.newInstance();
					ft.add(R.id.fragment_container_fl, mProductsFragment, TAB_TAG_PRODUCTS_FRAGMENT);
				}else {
					ft.show(mProductsFragment);
					((ProductsFragment)mProductsFragment).initData();
				}

				if (mProgressFragment != null) {
					((ProgressFragment)mProgressFragment).dismissPopupWindow();
				}
				break;
			case TAB_ID_PROGRESS_FRAGMENT:
				setTopBarVisible(false);
				mProgressBtn.setChecked(true);
				if (mProgressFragment == null){
					mProgressFragment = ProgressFragment.newInstance();
					ft.add(R.id.fragment_container_fl, mProgressFragment, TAB_TAG_PROGRESS_FRAGMENT);
				}else {
					ft.show(mProgressFragment);
					((ProgressFragment)mProgressFragment).initData();
				}
				break;
			case TAB_ID_PERSONAL_FRAGMENT:
				setTopBarVisible(false);
				mPersonalBtn.setChecked(true);
				if (mPersonCenterFragment == null){
					mPersonCenterFragment = new PersonCenterFragment();
					ft.add(R.id.fragment_container_fl, mPersonCenterFragment, TAB_TAG_PERSONAL_FRAGMENT);
				}else {
					ft.show(mPersonCenterFragment);
				}
				if (mProgressFragment != null) {
					((ProgressFragment)mProgressFragment).dismissPopupWindow();
				}
				break;
				default:
					break;
		}
		ft.commitAllowingStateLoss();
	}

	/**
	 * 连续两s内进行点击 则突出应用
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
			long currentTime = System.currentTimeMillis();
			if ((currentTime - mFirstClickTime) > 2000) {
				mFirstClickTime = currentTime;
				showToast("再按一次退出!");
			} else {
				ImageIdManager.clearId();//删除图片
				finish();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onGetNoticeFailure() {

	}

	@Override
	public void onGetNotice(MainModel.NoticeBean noticeBean) {
		if ((null != mNoticeDialog && mNoticeDialog.isShowing())) {//如果第一次进来，没有设置手势密码，然后设置，后台推一条公告过来，就会出现冲突情况(公告在手势密码上面)
			mNoticeDialog.dismiss();
		}
		mNoticeDialog = new NoticeDialog(this, noticeBean, this);
		mNoticeDialog.show();
	}

	/**
	 * 弹出更新对话框 如果不同意退出应用 。否则强制更新
	 */
	@Override
	public void hasNewVersion(final boolean forceUpdate, final String url, String content, String title) {
		if (!forceUpdate && !UpdateService.isNeedCheckUpdate()) {
			mNoticePresenter.getNotice();
			return;
		}
		// TODO: 2017/5/3  升级弹框及处理
		try {//todo 临时解决，点击退出应用crash
			mUpdateService = new UpdateService();
			AlertDialog dialog = mUpdateService.showUpdateDialog(this, forceUpdate, url, content, title);
			dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
				@Override
				public void onDismiss(DialogInterface dialog) {
					if (!forceUpdate) {
						mNoticePresenter.getNotice();
					}
				}
			});
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					if (!forceUpdate) {
						mNoticePresenter.getNotice();
					}
				}
			});
		} catch (Exception e) {
			CLog.e(TAG, e.getMessage());
		}
	}

	@Override
	public void isNewestVersion() {
		mNoticePresenter.getNotice();
	}

	@Override
	public void checkNewVersionFailed() {
		mNoticePresenter.getNotice();
	}

	@Override
	public void onCloseNoticeDialog(String noticeId) {
		if (null != mNoticeDialog && mNoticeDialog.isShowing()) {
			mNoticeDialog.dismiss();
		}
		YJPH.getInstance().getPreferenceManager().savePreference(PreferenceConstants.SP_KEY_LAST_SHOWED_NOTICE_ID, noticeId);
	}

	/*public void setUnReadFlagVisible(boolean flag) {
		if (!flag) {
			mProgressBtn.showCirclePointBadge();
		} else {
			mProgressBtn.hiddenBadge();
		}
	}*/

	/**
	 * 接收推送消息的事件，设置消息红点是否可见
	 */
	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onEventMainThread(PushEvent bean) {
		CLog.i(TAG, "onEventMainThread(PushEvent)");
//		setUnReadFlagVisible(bean.isFlag());
	}

	@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
	public void onEventMainThread(IEvent.NetWorkEvent event) {
		if (event.mIsConnected && mHomeFragment != null) {
			((HomeFragment)mHomeFragment).loadBanner();
		}
		EventAgent.removeStickyEvent(event);
	}

	@Override
	public void jPushSuccess() {
		YJPH.getInstance().getPreferenceManager().savePreference(PreferenceConstants.SP_KEY_BIND_JPUSH_FLAG, true);
		if (JPushInterface.isPushStopped(YJPH.getInstance())) {
			JPushInterface.resumePush(YJPH.getInstance());
		}
	}

	@Override
	public void jPushFailure(String tips) {

	}
}
